//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    showLoading: true,
    noMoretip: false,
    page: 0,
    curId:'',
    goIntoView:'',
  },
  onLoad:function(e){
    var that = this;
    if (e && e.cate1) {
      that.setData({
        categoryId: e.cate1
      })
    }
    if (e && e.cate2) {
      that.setData({
        cursecondId: e.cate2
      })
    }
    // that.isTagpage();
  },
  onShow:function(){
    var that = this;
    app.setNavtitle('分类商品');
    app.setNavColor(that);
    if (!app.globalData.plumSession) {
      app.plumSessionCallback = plumSession => {
        that.requestGoodFl();
      }
    } else {
      that.requestGoodFl();
    }
    app.setCartnum();//更新购物车数量
  },
  requestGoodFl: function () {
    console.log("请求接口");
    var that = this;
    var data = {};
    data.map = 'applet_goods_category_list';
    wx.showLoading({
      title: '加载中'
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data.data);
        if (res.data.ec == 200) {
          var goodsFlList = res.data.data;
          if (goodsFlList && goodsFlList.length > 0) {
            var cateSecondlist = goodsFlList[0].subordinate;
            var cursecondId = '';
            if (cateSecondlist.length > 0) {
              cursecondId = cateSecondlist[0].id
            }
            if (that.data.categoryId){
              for (let j = 0; j < goodsFlList.length;j++){
                if (that.data.categoryId == goodsFlList[j].id){
                  cateSecondlist = goodsFlList[j].subordinate;
                }
              }
              that.setData({
                toViewCategoryId: 'category' + that.data.categoryId,
                cateSecondlist: cateSecondlist
              })
            }else{
              that.setData({
                categoryId: goodsFlList[0].id,
                toViewCategoryId: 'category' + goodsFlList[0].id,
                cateSecondlist: cateSecondlist,
                cursecondId: cursecondId
              })
            }
          }
          that.requestAllGoods('one');
          that.setData({
            goodsFlList: res.data.data,
          })
        } else {
          console.log(res.data)
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  },
  toggleSecondfl:function(e){
    var that = this;
    var id = e.currentTarget.dataset.id;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true,
      cursecondId:id,
      goIntoView:'secondfl'+id,
      shopGoods: null
    })
    that.requestAllGoods();
  },
  requestAllGoods: function (type){
    var that = this;
    var data = {};
    var page = that.data.page;
    data.map = 'applet_mall_category_goodsList';
    data.page = page;
    data.cate = that.data.categoryId ? that.data.categoryId:'';
    data.secondCate = that.data.cursecondId ? that.data.cursecondId : '';
    console.log(data);
    if (type == 'one') {
      wx.showLoading({
        title: '加载中',
      })
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          var allArr = [];
          var initArr = that.data.shopGoods ? that.data.shopGoods:'[]';
          var curArr = res.data.data.goods;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data.goods
          }
          if(type=='one'){
            that.setData({
              oneFl: res.data.data.category,
              curId: res.data.data.category && res.data.data.category.length > 0 ? res.data.data.category[0].id:'',
              goIntoView: res.data.data.category && res.data.data.category.length > 0 ? 'onefl'+res.data.data.category[0].id : ''
            })
          }
          that.setData({
            shopGoods: allArr.length > 0 ? allArr : [],
            cartNum: res.data.data.cartNum
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          console.log(that.data.shopGoods);
        } else {
          console.log(res.data)
          if (page <= 0) {
            that.setData({
              shopGoods: []
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        // if (type == 'one') {
        //   wx.hideLoading();
        // }
        wx.stopPullDownRefresh();
      }
    });
  },
  onPullDownRefresh: function () {
    var that = this;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true,
      categoryId:''
    });
    that.requestGoodFl();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.requestAllGoods();
    }
  },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/goodDetail/goodDetail?id=' + goodId
    })
  },
  changeShowType: function (e) {
    var type = e.target.dataset.type;
    this.setData({
      showType: type
    })
  },
  searchPage: function () {
    wx.navigateTo({
      url: '/pages/searchList/searchList'
    })
  },
  toCartPage: function () {
    wx.navigateTo({
      url: '/subpages/mycart/mycart'
    })
  },
  //打开弹窗
  openModel: function () {
    var that = this;
    that.setData({
      modelShow: true
    })
  },
  //关闭弹窗
  closeModel: function () {
    var that = this;
    that.setData({
      modelShow: false
    })
  },
  //类型切换
  toggleChange: function (e) {
    var that = this;
    var categoryId = e.currentTarget.dataset.categoryid;
    var secondFl = e.currentTarget.dataset.second;
    if (e.currentTarget.dataset.model) {
      that.setData({
        modelShow: false
      });
    }
    that.setData({
      categoryId: categoryId,
      toViewCategoryId: 'category' + categoryId,
      cateSecondlist: secondFl,
      cursecondId: secondFl.length>0?secondFl[0].id:'',
      showLoading: true,
      noMoretip: false,
      page: 0,
    });
    that.requestAllGoods();
  },
  searchPage: function () {
    wx.navigateTo({
      url: '/pages/searchList/searchList'
    })
  },
  addminusCart: function (e) {
    var that = this;
    var curgood = e.currentTarget.dataset.curgood;
    var smallNum = curgood.smallNum;
    that.setData({
      curgood: curgood,
      buyNumber: smallNum,
      curImgformat:'',
      chooseGuige: {
        stock: curgood.stock
      },
      isShowFormat: true
    })
  },
  hideFormat: function () {
    var that = this;
    that.setData({
      isShowFormat: false
    })
  },
  stoptouchmove: function (e) {
    console.log(e);
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.target.dataset.findex;
    var index = e.target.dataset.index;
    var curgood = that.data.curgood;
    if (findex == 0) {
      var curImgformat = curgood.formatList[0].value[index];
      that.setData({
        curImgformat: curImgformat
      })
    }
    var checkFormat = [];
    for (var i = 0; i < curgood.formatList[findex].value.length; i++) {
      curgood.formatList[findex].value[i].checked = false;
    }
    curgood.formatList[findex].value[index].checked = true;
    for (var i = 0; i < curgood.formatList.length; i++) {
      for (var j = 0; j < curgood.formatList[i].value.length; j++) {
        if (curgood.formatList[i].value[j].checked) {
          checkFormat.push(curgood.formatList[i].value[j]);
        }
      }
    }
    that.setData({
      curgood: curgood,
      checkFormat: checkFormat
    })
    if (checkFormat.length == curgood.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
      }
      console.log(formatName);
      var chooseGuige = curgood.formatValue[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    }
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var buyNum = parseInt(that.data.buyNumber);
    var stock = parseInt(that.data.chooseGuige.stock);
    var purchase = parseInt(that.data.curgood.purchase);
    var disabled = e.currentTarget.dataset.disable;
    if (disabled) return;
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
      }
      if (buyNum < stock) {
        if (buyNum < purchase) {
          buyNum++;
        } else {
          app.errorTip(that, '超出限购数量', 2000);
        }
      } else {
        buyNum = stock;
      }
    } else {
      var smallNum = that.data.curgood.smallNum > 1 ? that.data.curgood.smallNum : 1;
      if (buyNum > smallNum) {
        buyNum--;
      } else {
        buyNum = smallNum;
      }
    }

    that.setData({
      buyNumber: buyNum
    })
  },
  numChange: function (e) {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if ((parseInt(val)) > parseInt(stock)) {
      that.setData({
        buyNumber: stock
      })
    } else {
      that.setData({
        buyNumber: val
      })
    }
  },
  confirmAddcart: function (e) {
    var that = this;
    var curgoodCart = that.data.curgoodCart;
    var gid = e.currentTarget.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = parseInt(that.data.buyNumber);
    var isFormat = that.data.curgood.hasFormat;
    var stock = parseInt(that.data.chooseGuige.stock);
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num,
      add: 1
    }
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!data.num || data.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + data.num);
    if (data.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            isShowFormat: false,
            cartNum: res.data.data.cartNum
          })
          that.hideFormat();
          app.errorTip(that, '已成功加入购物车', 2000);
          app.globalData.requestCartNum = res.data.data.cartNum;
          app.setCartnum();//更新购物车数量
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
      }
    });
  },
  
  backsy: function () {
    app.backHome();
  },
  onShareAppMessage: function () {
    var that = this;
    var title = '分类商品';
    var shareInfo = app.globalData.shareInfo;
    title = shareInfo.shareTitle ? shareInfo.shareTitle : title;
    app.getPoint(that);
    var cate1 = that.data.categoryId ? that.data.categoryId : '';
    var cate2 = that.data.cursecondId ? that.data.cursecondId : '';
    return {
      title: title,
      path: '/pages/fenleiGoods/fenleiGoods?cate1=' + cate1 + '&cate2=' + cate2
    }
  },
})